package com.newlink.building.userinfo.activity

import android.Manifest
import android.content.Context
import android.content.Intent
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.newlink.building.common_base.base.NL_BaseMvpActivity
import com.newlink.building.common_base.constant.Base_Constant
import com.newlink.building.common_base.ext.showToast
import com.newlink.building.common_base.ext.showToastLong
import com.newlink.building.common_base.model.bean.DeviceData
import com.newlink.building.common_base.model.bean.KitDeviceData
import com.newlink.building.common_base.utils.PermissionHelper
import com.newlink.building.common_base.utils.RegexUtils
import com.newlink.building.common_base.widget.CustomDialog
import com.newlink.building.common_base.widget.SpaceItemDecoration
import com.newlink.building.userinfo.R
import com.newlink.building.userinfo.adapter.Module_UserInfo_AreaSelectionAdapter
import com.newlink.building.userinfo.bean.Module_UserInfo_CheckBean
import com.newlink.building.userinfo.databinding.ActivityDeviceAddBinding
import com.newlink.building.userinfo.mvp.Module_UserInfo_DeviceSettingPresenter
import com.newlink.building.userinfo.mvp.contract.Module_UserInfo_DeviceSettingContract
import com.newlink.building.obfuscation.Module_Obfuscation_ObfuscationHelper
import com.newlink.building.obfuscation.Module_Obfuscation_ObfuscationInvoker
import java.util.regex.Pattern


/**
 * Created by xiaodong on 2024/12/13.
 */
class Module_UserInfo_DeviceAddActivityNL :
    NL_BaseMvpActivity<Module_UserInfo_DeviceSettingContract.View, Module_UserInfo_DeviceSettingContract.Presenter>(),
    Module_UserInfo_DeviceSettingContract.View {
    private lateinit var mBinding: ActivityDeviceAddBinding

    companion object {
        const val CODE_GET_MAC = 0x2001
    }

    private var mDevName: String? = ""
    private var mDevMac: String? = ""
    private var mDevType: Int = 0
    private var selectCheckBean: Module_UserInfo_CheckBean? = null
    private var deviceTypeBeans = arrayListOf<Module_UserInfo_CheckBean>()
    private var deleteAndAdd = false
    override fun attachLayoutRes(): View? {
        mBinding = ActivityDeviceAddBinding.inflate(layoutInflater)
        return mBinding.root
    }

    override fun initData() {
        mDevName = intent.getStringExtra(Base_Constant.KEY_DEVICE_NAME)
        mDevType = intent.getIntExtra(Base_Constant.KEY_DEVICE_TYPE, 0)
        mDevMac = intent.getStringExtra(Base_Constant.KEY_DEVICE_MAC)
        deviceTypeBeans = getSupportDeviceTypes()


        for (item in deviceTypeBeans) {
            if (mDevType != 0) {
                if (item.value == mDevType.toString()) {
                    selectCheckBean = item
                }
            }
        }
        mBinding.etDeviceType.setText(selectCheckBean?.name)

    }

    override fun createPresenter(): Module_UserInfo_DeviceSettingContract.Presenter {
        return Module_UserInfo_DeviceSettingPresenter()
    }

    override fun initView() {
        // 设备添加页面初始化时的混淆
        Module_Obfuscation_ObfuscationHelper.onMethodEnter("DeviceAddActivity", "initView")
        Module_Obfuscation_ObfuscationInvoker.invokeRandom(mDevMac?.hashCode() ?: 0)

        if (!mDevMac.isNullOrEmpty()) {
            mBinding.titleBar.tvTitleBarCenter.text = getString(R.string.device_edit)
        } else {
            mBinding.titleBar.tvTitleBarCenter.text = getString(R.string.device_add)
        }

        mBinding.etDeviceName.setText(mDevName)
        mBinding.etDeviceMac.setText(mDevMac)

        mBinding.etDeviceName.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun afterTextChanged(p0: Editable?) {
                checkSubmitBtnState()
            }

        })

        mBinding.etDeviceMac.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun afterTextChanged(p0: Editable?) {
                checkSubmitBtnState()
            }

        })

        mBinding.btnSubmit.setOnClickListener {
            val devName = mBinding.etDeviceName.text.toString()
            var devMac = formatNoSymbolMac(mBinding.etDeviceMac.text.toString())
            val hasSpecial = checkSpecialCharacter(devName)
            if (hasSpecial) {
                val regex = "`%&\\\\<>'\""
                showToastLong(getString(R.string.device_name_contains_special_characters, regex))
                return@setOnClickListener
            }

            if (selectCheckBean == null) {
                showToast(getString(R.string.device_type_no_select))
                return@setOnClickListener
            }

            if (devMac.isEmpty()) {
                showToast(getString(R.string.device_mac_not_empty))
                return@setOnClickListener
            }

            if (!RegexUtils.checkMac(devMac)) {
                showToast(getString(R.string.incorrect_mac_address))
                return@setOnClickListener
            }
            val doorNo = if (selectCheckBean!!.value.toInt() == 2) 1 else 0

            if (!mDevMac.isNullOrEmpty()) {
                if (mDevMac == devMac) {
                    mPresenter?.editKitDevice(
                        accessToken,
                        KitDeviceData(
                            name = devName,
                            mac = devMac,
                            type = selectCheckBean!!.value.toInt(),
                            doorNo
                        )
                    )
                } else {
                    val promptTitle = getString(R.string.device_mac_change)
                    CustomDialog(this).setMessage(promptTitle)
                        .setPositiveButton(object : CustomDialog.OnClickListener {
                            override fun onClick(dialog: CustomDialog) {
                                deleteAndAdd = true
                                val devName = mBinding.etDeviceName.text.toString()
                                var devMac = formatNoSymbolMac(mBinding.etDeviceMac.text.toString())
                                selectCheckBean?.let {
                                    mPresenter?.addKitDevice(
                                        accessToken,
                                        KitDeviceData(devName, devMac, it.value.toInt(), doorNo)
                                    )
                                }
//                                mPresenter?.deleteKitDevice(accessToken, mDevMac!!)
                            }

                        }).setNegativeButton(object : CustomDialog.OnClickListener {
                            override fun onClick(dialog: CustomDialog) {
                                dialog.dismiss()
                            }

                        }).show()
                }

                return@setOnClickListener
            }

            mPresenter?.addKitDevice(
                accessToken,
                KitDeviceData(
                    name = devName,
                    mac = devMac,
                    type = selectCheckBean!!.value.toInt(),
                    doorNo
                )
            )

        }

        mBinding.ivScan.setOnClickListener {
            if (!PermissionHelper.required(this).hasPermission(Manifest.permission.CAMERA)) {
                requestPermissions(arrayOf(Manifest.permission.CAMERA), 0)
            } else {
                jumpToCapture()
            }
        }

        mBinding.etDeviceType.setOnClickListener {
            showBottomSheetDialog(this, deviceTypeBeans)
        }

        checkSubmitBtnState()
    }

    //服务器禁止带的特殊字符,影响sql查询
    private fun checkSpecialCharacter(str: String): Boolean {
        val regex = "[`%&\\\\<>'\"]"
        // 创建Pattern对象
        val pattern = Pattern.compile(regex)
        // 创建Matcher对象
        val matcher = pattern.matcher(str)
        return matcher.find()
    }

    private fun formatNoSymbolMac(devMac: String): String {
        var mac = devMac
        if (devMac.contains(":")) {
            mac = devMac.replace(":", "")
        }

        if (devMac.contains("-")) {
            mac = devMac.replace("-", "")
        }
        return mac

    }

    private fun jumpToCapture() {
        startActivityForResult(Intent(this, Module_UserInfo_DeviceMacScanActivityNL::class.java), CODE_GET_MAC)
//        ARouter.getInstance().build(RouterPath.PATH_SCAN).withString(FvlKey.EXTRA_TITLE, getString(R.string.device_add_scan_title)).navigation(this, CODE_GET_MAC)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (resultCode == RESULT_OK && requestCode == CODE_GET_MAC) {
            data?.let {
                val type = it.getIntExtra("type", 0)
                it.getStringExtra("data")?.let { data ->
                    if (!RegexUtils.checkMac(data)) {
                        showToast(
                            if (type == 1) getString(R.string.invalid_bar_code) else getString(
                                R.string.invalid_qr_code
                            )
                        )
                    }
                    mBinding.etDeviceMac.setText(data)
                }
            }
        }

    }


    private fun checkSubmitBtnState() {
        mBinding.btnSubmit.isEnabled =
            mBinding.etDeviceName.text.isNotEmpty() && mBinding.etDeviceMac.text.isNotEmpty() && selectCheckBean != null
        mBinding.btnSubmit.setTextColor(
            if (mBinding.btnSubmit.isEnabled) getColor(R.color.white) else getColor(
                R.color.disabled_text_color
            )
        )
    }

    private fun showBottomSheetDialog(context: Context, cbs: MutableList<Module_UserInfo_CheckBean>) {
        val bottomSheetDialog = BottomSheetDialog(context, R.style.BottomSheetDialog)
        bottomSheetDialog.setCanceledOnTouchOutside(false)
        val view = LayoutInflater.from(context).inflate(R.layout.dialog_device_add, null, false)
        val recyclerView = view.findViewById(R.id.recyclerView) as RecyclerView
        view.findViewById<TextView>(R.id.tv_cancel).setOnClickListener {
            //点取消后清除标记,再点击根据显示的名字重置标记
            for (item in cbs) {
                item.isChecked = false
            }
            bottomSheetDialog.dismiss()
        }

        val title = view.findViewById<TextView>(R.id.tv_title)
        title.text = resources.getString(R.string.device_type)
        val selecValue = mBinding.etDeviceType.text.toString()
        for (item in cbs) {
            if (item.name == selecValue) {
                item.isChecked = true
            }
        }
        view.findViewById<TextView>(R.id.tv_confirm).setOnClickListener {

            var selectType = ""
            for (item in cbs) {
                if (item.isChecked) {
                    selectType = item.name
                }
            }
            mBinding.etDeviceType.setText(selectType)
            checkSubmitBtnState()
            bottomSheetDialog.dismiss()
        }
        val mAdapter = Module_UserInfo_AreaSelectionAdapter(cbs)
        recyclerView.adapter = mAdapter
        recyclerView.addItemDecoration(SpaceItemDecoration(context))
        mAdapter.setOnItemClickListener { adapter, _, position ->

            selectCheckBean = cbs[position]

            for ((index, item) in cbs.withIndex()) {
                item.isChecked = index == position
            }

            adapter.notifyDataSetChanged()
        }

        bottomSheetDialog.setContentView(view)
        bottomSheetDialog.show()
    }

    fun getSupportDeviceTypes(): ArrayList<Module_UserInfo_CheckBean> {
        val deviceTypeBeans: ArrayList<Module_UserInfo_CheckBean> = arrayListOf()
        deviceTypeBeans.add(Module_UserInfo_CheckBean(getString(R.string.device_indoor_phone), "1", 1, false))
        deviceTypeBeans.add(Module_UserInfo_CheckBean(getString(R.string.device_access_control), "2", 1, false))
        return deviceTypeBeans
    }

    override fun refreshDeviceList(total: Int, data: MutableList<DeviceData>) {
    }

    override fun editDeviceResult(success: Boolean) {
        showToast(if (success) getString(R.string.default_change_success) else getString(R.string.default_change_fail))
        if (success) {
            setResult(RESULT_OK)
            finish()
        }
    }

    override fun addDeviceResult(success: Boolean) {
        if (deleteAndAdd) {
            mPresenter?.deleteKitDevice(accessToken, mDevMac!!)
        } else {
            setResult(RESULT_OK)
            finish()
        }
    }

    override fun deleteDeviceResult(success: Boolean) {
        setResult(RESULT_OK)
        finish()
    }
}